﻿using BuyThePeople.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BuyThePeople.Composition;

namespace BuyThePeople.Controllers
{
    public class UserController : Controller
    {
        private string beforeUri { get; set; }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // 로그인 페이지를 호출 전 이전 Url을 저장한다.
            if ((Request != null)
                && (Request.UrlReferrer != null)
                && (Request.Url.AbsoluteUri.ToLower().Contains("/user/") == true))
            {
                beforeUri = Request.UrlReferrer.AbsoluteUri;
            }
            if (string.IsNullOrEmpty(beforeUri) == false)
            {
                ViewBag.Url = beforeUri;
            }
            base.OnActionExecuting(filterContext);
        }

        public UserController()
        {
            ViewBag.Title = "로그인";
            ViewBag.Style = "";
        }
        
        //
        // GET: /User/
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(T_USER user)
        {
            return Redirect(ConstFactory.UrlHome);
        }

        [HttpGet]
        public ActionResult Join()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Join(T_USER user, string url)
        {
            DataModelsDataContext dmdc = new DataModelsDataContext();
            try
            {
                dmdc.T_USER.InsertOnSubmit(user);
                dmdc.SubmitChanges();
            }
            catch (Exception ex)
            {

            }
            if (string.IsNullOrEmpty(url) == false)
            {
                return Redirect(url);
            }
            return Redirect(ConstFactory.UrlHome);
        }
        
        [HttpGet]
        public ActionResult Login(string url)
        {
            if (Session[ConstFactory.SessionUser] is UserLoginData)
            {
                UserLoginData user = Session[ConstFactory.SessionUser] as UserLoginData;
                if (string.IsNullOrEmpty(url) == false)
                {
                    return Redirect(url);
                }
                return Redirect(ConstFactory.UrlHome);
            }
            else
            {
                ViewBag.Url = url;
                return View();
            }
        }

        [HttpPost]
        public ActionResult Login(string id, string pw, string url)
        {
            DataModelsDataContext dmdc = new DataModelsDataContext();
            T_USER user = dmdc.T_USER.FirstOrDefault(fn => fn.ID == id && fn.Password == pw);
            
            if (user != null)
            {
                UserLoginData userLog = new UserLoginData() {
                    UserSeq = user.UserSeq,
                    ID = user.ID,
                    Name = user.Name,
                    IsSeller = user.IsSeller == true
                };
                Session[ConstFactory.SessionUser] = userLog;
                if (string.IsNullOrEmpty(url) == false)
                {
                    return Redirect(url);
                }
                return Redirect(ConstFactory.UrlHome);
            }
            else
            {
                ViewBag.Result = "아이디가 없거나 비밀번호가 맞지 않습니다.";
                return View();
            }
        }

        public ActionResult Logout()
        {
            if (Session[ConstFactory.SessionUser] is UserLoginData)
            {
                Session.RemoveAll();
            }
            return Redirect(ConstFactory.UrlHome);
        }

        public ActionResult UserInfo()
        {
            if (Session[ConstFactory.SessionUser] is UserLoginData)
            {
                UserLoginData logdata = Session[ConstFactory.SessionUser] as UserLoginData;
                DataModelsDataContext dmdc = new DataModelsDataContext();
                T_USER user = dmdc.T_USER.FirstOrDefault(fn => fn.UserSeq == logdata.UserSeq);
                if (user.IsSeller == null)
                {
                    user.IsSeller = false;
                }
                if (user != null)
                {
                    return View(user);
                }
            }
            return Redirect(ConstFactory.UrlLogin);
        }

        [HttpPost]
        public ActionResult UserInfo(T_USER user)
        {
            if (Session[ConstFactory.SessionUser] is UserLoginData)
            {
                UserLoginData logdata = Session[ConstFactory.SessionUser] as UserLoginData;
                DataModelsDataContext dmdc = new DataModelsDataContext();
                T_USER userdb = dmdc.T_USER.FirstOrDefault(fn => fn.UserSeq == logdata.UserSeq);
                if (userdb != null)
                {
                    userdb.Telephone = user.Telephone;
                    userdb.Email = user.Email;
                    userdb.Address = user.Address;
                    userdb.AddressDetail = user.AddressDetail;
                    userdb.IsSeller = user.IsSeller;
                    if (string.IsNullOrEmpty(user.Password) == false)
                    {
                        userdb.Password = user.Password;
                    }
                    dmdc.SubmitChanges();
                    logdata.IsSeller = userdb.IsSeller == true;
                    return View(user);
                }
            }
            return Redirect(ConstFactory.UrlLogin);
        }

        public ActionResult AddJointList(JointPurchaseType id = JointPurchaseType.None)
        {
            if (Session[ConstFactory.SessionUser] is UserLoginData)
            {
                UserLoginData logdata = Session[ConstFactory.SessionUser] as UserLoginData;
                DataModelsDataContext dmdc = new DataModelsDataContext();
                UserForJointPurchaseData user = new UserForJointPurchaseData();
                DateTime dtNow = DateTime.Now;
                string page = string.Empty;
                user.User = dmdc.T_USER.FirstOrDefault(fn => fn.UserSeq == logdata.UserSeq);
                switch (id)
                {
                    case JointPurchaseType.None:
                    case JointPurchaseType.Participation:
                        {
                            ViewBag.Title = "마이페이지 공구참여내역";
                            var goodslist = from j in dmdc.T_JOINTPURCHASE
                                            join g in dmdc.T_GOODS on j.GoodsSeq equals g.GoodsSeq
                                            where j.UserSeq == user.User.UserSeq && g.JoinDateEnd > dtNow
                                                && g.DeleteDate == null && j.DeleteDate == null
                                            select new KeyValuePair<T_JOINTPURCHASE, T_GOODS>(j, g);
                            int cnt = goodslist.Count();
                            if (cnt > 0)
                            {
                                user.JointList = goodslist.ToDictionary(x => x.Key, x => x.Value);
                            }
                            else
                            {
                                user.JointList = new Dictionary<T_JOINTPURCHASE, T_GOODS>();
                            }
                            page = "~/Views/Shared/EditorTemplates/JointListTemplateIng.cshtml";
                        }
                        break;
                    case JointPurchaseType.Termination:
                    default:
                        {
                            ViewBag.Title = "마이페이지 공구종료내역";
                            var goodslist = from j in dmdc.T_JOINTPURCHASE
                                            join g in dmdc.T_GOODS on j.GoodsSeq equals g.GoodsSeq
                                            where j.UserSeq == user.User.UserSeq && g.JoinDateEnd <= dtNow
                                                && g.DeleteDate == null && j.DeleteDate == null
                                            select new KeyValuePair<T_JOINTPURCHASE, T_GOODS>(j, g);
                            int cnt = goodslist.Count();
                            if (cnt > 0)
                            {
                                user.JointList = goodslist.ToDictionary(x => x.Key, x => x.Value);
                            }
                            else
                            {
                                user.JointList = new Dictionary<T_JOINTPURCHASE, T_GOODS>();
                            }
                            page = "~/Views/Shared/EditorTemplates/JointListTemplateEnd.cshtml";
                        }
                        break;
                    case JointPurchaseType.Bid:
                        {
                            ViewBag.Title = "마이페이지 셀러";
                            var goodslist = from b in dmdc.T_BIDDING
                                            join g in dmdc.T_GOODS on b.GoodsSeq equals g.GoodsSeq
                                            where b.UserSeq == user.User.UserSeq && g.JoinDateEnd > dtNow
                                                && g.DeleteDate == null && b.DeleteDate == null
                                            select new KeyValuePair<T_BIDDING, T_GOODS>(b, g);
                            int cnt = goodslist.Count();
                            if (cnt > 0)
                            {
                                user.BidList = goodslist.ToDictionary(x => x.Key, x => x.Value);
                            }
                            else
                            {
                                user.BidList = new Dictionary<T_BIDDING, T_GOODS>();
                            }
                            page = "~/Views/Shared/EditorTemplates/JointListTemplateSeller.cshtml";
                        }
                        break;
                }
                return PartialView(page, user);
            }
            else
            {
                return View();
            }
        }

        public ActionResult UserJointPurchase(JointPurchaseType id = JointPurchaseType.None)
        {
            if (Session[ConstFactory.SessionUser] is UserLoginData)
            {
                switch (id)
                {
                    case JointPurchaseType.None:
                    case JointPurchaseType.Participation:
                        {
                            ViewBag.ScriptBlock = "AddJointList(1);";
                        }
                        break;
                    case JointPurchaseType.Termination:
                    default:
                        {
                            ViewBag.ScriptBlock = "AddJointList(2);";
                        }
                        break;
                    case JointPurchaseType.Bid:
                        {
                            ViewBag.ScriptBlock = "AddJointList(3);";
                        }
                        break;
                }
                return View();
            }
            else
            {
                return Redirect(string.Format("{0}?url={1}", ConstFactory.UrlLogin, ConstFactory.UrlUserJointPurchase));
            }
        }
    }
}
